<script setup lang="ts">
import {
  NButton,
  NSpace,
  NDataTable,
  NInput,
  type DataTableColumns,
  NPagination,
  NForm,
  NFormItem,
  NSelect,
  useDialog,
  type SelectOption,
  useMessage,
  NModal,
  type FormRules,
  type FormInst
} from 'naive-ui'
import { h, onDeactivated, onMounted, onUnmounted, reactive, ref, shallowRef } from 'vue'
import TableView from '@/components/TableView.vue'
import type { HttpResponse, HttpResponsePagination } from '@/utils/http'
import EllipseAction from '@/views/common/EllipseAction'
import type { BatchTableRowModel, CommonSelectOptionModel } from '@/api/batch'
import useFlush from '@/hooks/useFlush'
import { useRouter } from 'vue-router'
import { sendRequest } from '@/utils/api'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'

useFlush('flushBatch', () => queryTableData())
const router = useRouter()
const dialog = useDialog()
const message = useMessage()

const djStatusOptions = shallowRef<CommonSelectOptionModel[]>([])
const djStatusLoading = ref(false)
const queryDjStatusOptions = async () => {
  try {
    djStatusLoading.value = true
    const [error, res] = await sendRequest<HttpResponse<CommonSelectOptionModel[]>>({
      module: 'batch',
      api: 'djStatusList'
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)

    djStatusOptions.value = res.data
  } catch (error) {
    console.log(error)
  } finally {
    djStatusLoading.value = false
  }
}

const identifyStatusOptions = shallowRef<CommonSelectOptionModel[]>([])
const identifyStatusLoading = ref(false)
const queryIdentifyStatusOptions = async () => {
  try {
    identifyStatusLoading.value = true
    const [error, res] = await sendRequest<HttpResponse<CommonSelectOptionModel[]>>({
      module: 'batch',
      api: 'identifyStatusList'
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)

    identifyStatusOptions.value = res.data
  } catch (error) {
    console.log(error)
  } finally {
    identifyStatusLoading.value = false
  }
}

const tableData = ref<BatchTableRowModel[]>([])
const tableLoading = ref(false)
const queryTableData = async (flush = false) => {
  if (flush) paginationReactive.page = 1
  try {
    tableLoading.value = true
    const [error, res] = await sendRequest<HttpResponsePagination<BatchTableRowModel>>({
      module: 'batch',
      api: 'list',
      override: {
        params: {
          limit: paginationReactive.pageSize,
          page: paginationReactive.page,
          batchName: formData.batchName || null,
          identifyStatusCode: formData.identifyStatusCode || null,
          pointStatusCode: formData.pointStatusCode || null,
          creator: formData.creator || null
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)

    tableData.value = res.data.list
    paginationReactive.itemCount = res.data.totalCount
  } catch (error) {
    console.log(error)
  } finally {
    tableLoading.value = false
  }
}

interface FormData {
  batchName: string | null
  identifyStatusCode: string | null
  pointStatusCode: string | null
  creator: string | null
}
const formData = reactive<FormData>({
  batchName: null,
  identifyStatusCode: null,
  pointStatusCode: null,
  creator: null
})
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})
const resetForm = () => {
  formData.batchName = null
  formData.identifyStatusCode = null
  formData.pointStatusCode = null
  formData.creator = null
}
const columns: DataTableColumns<BatchTableRowModel> = [
  {
    title: '批次编号',
    key: 'batchCode',
    width: '200rem'
  },
  {
    title: '批次名称',
    key: 'batchName'
  },
  {
    title: '点交状态',
    key: 'pointStatus'
  },
  {
    title: '鉴定状态',
    key: 'identifyStatus'
  },
  {
    title: '创建人',
    key: 'creator'
  },
  {
    title: '创建时间',
    key: 'createTime'
  },
  {
    title: '最后修改时间',
    key: 'updateTime'
  },
  {
    title: () => h('div', { style: 'text-align: center' }, '操作'),
    key: 'action',
    width: 380,
    fixed: 'right',
    render: (e) => {
      return h(EllipseAction, {
        actions: () =>
          [
            h(
              NButton,
              {
                color: '#6CB187',
                quaternary: true,
                size: 'small',
                style: {
                  display: e.detail ? 'inline-flex' : 'none'
                },
                onClick: () => {
                  router.push({
                    name: 'batchDetail',
                    params: {
                      id: e.id
                    },
                    query: {
                      isUnIdentify: String(e.identifyStatusCode === 'A4101'),
                      isNotRequired: String(e.identifyStatusCode === 'A4102'),
                      isIdentifyEnd: String(
                        e.identifyStatusCode === 'A4103' ||
                          (e.identifyStatusCode === 'A4104' && !e.identifyRegister)
                      ),
                      isIdentifying: String(e.identifyStatusCode === 'A4104' && e.identifyRegister),
                      redirect: router.currentRoute.value.fullPath
                    }
                  })
                }
              },
              { default: () => '详情' }
            ),
            h(
              NButton,
              {
                color: '#6CB187',
                quaternary: true,
                size: 'small',
                style: {
                  display: e.edit ? 'inline-flex' : 'none'
                },
                onClick() {
                  router.push({
                    name: 'editBatch',
                    params: {
                      id: e.id
                    },
                    query: {
                      redirect: router.currentRoute.value.fullPath
                    }
                  })
                }
              },
              { default: () => '编辑' }
            ),
            h(
              NButton,
              {
                color: '#FC355D',
                quaternary: true,
                size: 'small',
                style: {
                  display: e.delete ? 'inline-flex' : 'none'
                },
                onClick: () => handleDeleteBatch(e.id)
              },
              { default: () => '删除' }
            ),
            h(
              NButton,
              {
                color: '#6CB187',
                quaternary: true,
                size: 'small',
                style: {
                  display: e.identifyApply ? 'inline-flex' : 'none'
                },
                onClick() {
                  router.push({
                    name: 'identifyApply',
                    params: {
                      id: e.id
                    },
                    query: {
                      redirect: router.currentRoute.value.fullPath
                    }
                  })
                }
              },
              { default: () => '鉴定申请' }
            ),
            h(
              NButton,
              {
                color: '#6CB187',
                quaternary: true,
                size: 'small',
                style: {
                  display: e.identifyRegister ? 'inline-flex' : 'none'
                },
                onClick: () => {
                  router.push({
                    name: 'registerTF',
                    params: {
                      id: e.id
                    },
                    query: {
                      redirect: router.currentRoute.value.fullPath
                    }
                  })
                }
              },
              { default: () => '鉴定登记' }
            ),
            h(
              NButton,
              {
                color: '#6CB187',
                quaternary: true,
                size: 'small',
                style: {
                  display: e.noNeed ? 'inline-flex' : 'none'
                },
                onClick: () => handleNotIdentity(e.id)
              },
              { default: () => '无需鉴定' }
            ),
            h(
              NButton,
              {
                color: '#6CB187',
                quaternary: true,
                size: 'small',
                style: {
                  display: e.finished ? 'inline-flex' : 'none'
                },
                onClick: () => handleEndIdentity(e.id)
              },
              { default: () => '结束鉴定' }
            ),
            h(
              NButton,
              {
                color: '#6CB187',
                quaternary: true,
                size: 'small',
                style: {
                  display: e.click ? 'inline-flex' : 'none'
                },
                onClick: () => {
                  router.push({
                    name: 'dJ',
                    params: {
                      id: e.id
                    },
                    query: {
                      redirect: router.currentRoute.value.fullPath
                    }
                  })
                }
              },
              { default: () => '点交' }
            ),
            h(
              NButton,
              {
                color: '#6CB187',
                quaternary: true,
                size: 'small',
                style: {
                  display: e.clickConfirm ? 'inline-flex' : 'none'
                },
                onClick: () => {
                  router.push({
                    name: 'dJConfirm',
                    params: {
                      id: e.id
                    },
                    query: {
                      redirect: router.currentRoute.value.fullPath
                    }
                  })
                }
              },
              { default: () => '点交确认' }
            ),
            h(
              NButton,
              {
                color: '#6CB187',
                quaternary: true,
                size: 'small',
                style: {
                  display: e.temporary ? 'inline-flex' : 'none'
                },
                onClick: () => {
                  // @ts-ignore
                  formValue.batchId = e.id
                  dJSaveModalVisible.value = true
                }
              },
              { default: () => '暂存' }
            ),
            h(
              NButton,
              {
                color: '#6CB187',
                quaternary: true,
                size: 'small',
                style: {
                  display: e.supplement ? 'inline-flex' : 'none'
                },
                onClick: () => {
                  router.push({
                    name: 'addAttachments',
                    params: {
                      id: e.id
                    },
                    query: {
                      redirect: router.currentRoute.value.fullPath
                    }
                  })
                }
              },
              { default: () => '补充附件' }
            )
          ].filter((item) => (!item.props?.style ? true : item.props?.style.display !== 'none'))
      })
    }
  }
]

const dJSaveModalVisible = ref(false)
const djSaveFormInst = ref<FormInst | null>(null)
const formValue = reactive({
  batchId: null,
  remark: null,
  storagePlace: null
})
const rules: FormRules = {
  storagePlace: {
    required: true,
    message: '请输入存放位置',
    trigger: ['blur', 'input']
  }
}
const handleDJSave = () => {
  djSaveFormInst.value?.validate(async (err) => {
    if (err) return
    try {
      const [error, res] = await sendRequest({
        module: 'batch',
        api: 'temporaryStorage',
        override: {
          data: formValue
        }
      })
      if (error) throw error
      if (res.code !== 0) throw new Error(res.msg)

      message.success('暂存成功！')
      formValue.remark = null
      formValue.storagePlace = null
      queryTableData()
    } catch (error) {
      if (error instanceof Error) {
        message.error(error.message)
      }
    } finally {
      dJSaveModalVisible.value = false
    }
  })
}

const modalVisible = ref(false)
const modalTitle = ref('')
const modalContent = ref('')
const modalConfirm = ref<(() => Promise<void>) | null>()
const handleModalClose = () => {
  modalVisible.value = false
  modalTitle.value = ''
  modalContent.value = ''
  modalConfirm.value = null
}

const handleNotIdentity = (id: number) => {
  modalVisible.value = true
  modalTitle.value = '提示'
  modalContent.value = '是否对当前物品结束鉴定？'
  modalConfirm.value = async () => {
    try {
      const [error, res] = await sendRequest({
        module: 'batch',
        api: 'withoutIdentify',
        override: {
          params: {
            batchId: id
          }
        }
      })
      if (error) throw error
      if (res.code !== 0) throw new Error(res.msg)
      message.success(res.msg)
      queryTableData()
      modalVisible.value = false
    } catch (error: any) {
      message.error(error.message)
    }
  }
}

const handleEndIdentity = (id: number) => {
  modalVisible.value = true
  modalTitle.value = '提示'
  modalContent.value = '是否对当前物品结束鉴定？'
  modalConfirm.value = async () => {
    try {
      const [error, res] = await sendRequest({
        module: 'batch',
        api: 'finishIdentify',
        override: {
          params: {
            batchId: id
          }
        }
      })
      if (error) throw error
      if (res.code !== 0) throw new Error(res.msg)
      message.success(res.msg)
      queryTableData()
      modalVisible.value = false
    } catch (error: any) {
      message.error(error.message)
    }
  }
}

const handleDeleteBatch = (id: number) => {
  modalVisible.value = true
  modalTitle.value = '提示'
  modalContent.value = '是否删除当前批次？'
  modalConfirm.value = async () => {
    try {
      const [error, res] = await sendRequest({
        module: 'batch',
        api: 'delete',
        override: {
          data: [id]
        }
      })
      if (error) throw error
      if (res.code !== 0) throw new Error(res.msg)
      message.success(res.msg)
      queryTableData()
      modalVisible.value = false
    } catch (error: any) {
      message.error(error.message)
    }
  }
}
const isAdd = ref(false)
const queryCheckUserInZjb = async () => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'collectNotice',
    api: 'checkUserInZjb'
  })
  if (error) return message.error(error.message)
  isAdd.value = res.data
}
onMounted(() => {
  Promise.allSettled([
    queryDjStatusOptions(),
    queryTableData(),
    queryIdentifyStatusOptions(),
    queryCheckUserInZjb()
  ])
})
onUnmounted(() => {
  dialog.destroyAll()
  modalConfirm.value = null
  modalContent.value = ''
  modalTitle.value = ''
  modalVisible.value = false
})
onDeactivated(() => {
  dialog.destroyAll()
  modalConfirm.value = null
  modalContent.value = ''
  modalTitle.value = ''
  modalVisible.value = false
})
</script>

<template>
  <TableView class="batch">
    <template #form>
      <NSpace justify="space-between">
        <NSpace align="center">
          <NForm
            label-placement="left"
            :show-feedback="false"
            inline
            @keydown.enter="queryTableData(true)"
          >
            <NFormItem label="批次名称：">
              <NInput
                v-model:value="formData.batchName"
                placeholder="请输入批次名称"
                clearable
              />
            </NFormItem>
            <NFormItem label="鉴定状态：">
              <NSelect
                :loading="identifyStatusLoading"
                :options="(identifyStatusOptions as unknown as SelectOption[])"
                v-model:value="formData.identifyStatusCode"
                label-field="name"
                placeholder="请选择鉴定状态"
                style="width: 180rem"
                clearable
              />
            </NFormItem>
            <NFormItem label="点交状态：">
              <NSelect
                :loading="djStatusLoading"
                :options="(djStatusOptions as unknown as SelectOption[])"
                v-model:value="formData.pointStatusCode"
                label-field="name"
                placeholder="请选择点交状态"
                style="width: 180rem"
                clearable
              />
            </NFormItem>
            <NFormItem label="创建人：">
              <NInput
                v-model:value="formData.creator"
                placeholder="请输入创建人"
                clearable
              />
            </NFormItem>
          </NForm>
          <NButton
            :disabled="tableLoading"
            :loading="tableLoading"
            color="#6CB187"
            ghost
            style="min-width: 78rem"
            @click="queryTableData(true)"
          >
            查询
          </NButton>
          <NButton
            :disabled="tableLoading"
            color="#6CB187"
            style="min-width: 78rem"
            @click="resetForm"
            ghost
          >
            重置
          </NButton>
        </NSpace>

        <NButton
          color="#6CB187"
          style="min-width: 115rem"
          v-if="isAdd"
          @click="
            $router.push({
              name: 'addBatch',
              query: {
                redirect: $route.fullPath
              }
            })
          "
        >
          新增批次
        </NButton>
      </NSpace>
    </template>
    <template #table="props">
      <n-data-table
        v-bind="props"
        :data="tableData"
        :columns="columns"
        :loading="tableLoading"
        bordered
      />
    </template>
    <template #pagination>
      <NPagination
        show-size-picker
        show-quick-jumper
        :page-sizes="paginationReactive.pageSizes"
        :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page"
        :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange"
        @update:page-size="paginationReactive.onUpdatePageSize"
      >
        <template #suffix>页</template>
        <template #prefix>
          <span style="font-size: 14px">共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>

  <NModal
    :auto-focus="false"
    v-model:show="modalVisible"
  >
    <VDialogContent
      @close="handleModalClose"
      @submit="modalConfirm && modalConfirm()"
      :title="modalTitle"
    >
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        {{ modalContent }}
      </div>
    </VDialogContent>
  </NModal>

  <NModal
    :auto-focus="false"
    v-model:show="dJSaveModalVisible"
  >
    <VDialogContent
      @close="dJSaveModalVisible = false"
      @submit="handleDJSave"
      title="存放地"
    >
      <NSpace>
        <NForm
          ref="djSaveFormInst"
          :model="formValue"
          :rules="rules"
          label-placement="left"
          :label-width="85"
          label-align="right"
        >
          <NSpace>
            <NFormItem
              label="存放位置:"
              path="storagePlace"
            >
              <NInput
                v-model:value="formValue.storagePlace"
                placeholder="请输入存放位置"
                clearable
                style="width: 250px"
              />
            </NFormItem>
          </NSpace>
          <NSpace>
            <NFormItem
              label="备注:"
              path="remark"
            >
              <NInput
                v-model:value="formValue.remark"
                placeholder="请输入备注"
                clearable
                type="textarea"
                style="width: 250px"
              />
            </NFormItem>
          </NSpace>
        </NForm>
      </NSpace>
    </VDialogContent>
  </NModal>
</template>

<style scoped lang="scss">
.batch {
  padding: 29rem 30rem;
  gap: 25rem 0;
}
</style>
